package com.usian.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(1)
@Component
public class LoginFilter implements  GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();
        if(path.contains("login")){
            return chain.filter(exchange);
        }else{
            String token = request.getQueryParams().getFirst("token");
            if(token!="" && token!=null){
                Integer userId =(Integer) redisTemplate.boundValueOps(token).get();
                if(userId==null){
                    //用户未登录  登录失效
                    String url ="http://localhost:8083/login";
                    response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                    response.getHeaders().set(HttpHeaders.LOCATION,url);
                    return response.setComplete();
                }
            }else{
                //用户未登录  没有登录信息
                String url ="http://localhost:8083/login";
                response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                response.getHeaders().set(HttpHeaders.LOCATION,url);
                return response.setComplete();
            }
        }
        return  chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
